
let state = -1;//查询所有
let timer = null
layui.config({
    version: '1510164124181'
}).use(['form', 'laypage', 'layer', 'element', 'laydate'], function () {
    form = layui.form;
    layer = layui.layer;
    laypage = layui.laypage;//分页
    element = layui.element; //元素操作
    laydate = layui.laydate;//时间选择器
    //日期时间范围
    laydate.render({
        elem: '#order_time'
        , type: 'datetime'
        , range: true
    });
    $(".mystate a").click(function () {
        $(".mystate a").removeClass("red");
        $(this).addClass("red");
        state = $(this).attr("data-id");
        $("#state option[value=" + state + "]").attr("selected", "selected");
        SearchInfo();
    });
    inituserdata();

});
function ExprotRefundRecord() {
    let handle_type = $("#handle_type").val();
    let pro_name = $("#pro_name").val();//宝贝名称
    let order_time = $("#order_time").val();//下单时间
    let startTime = order_time.split(" - ")[0]||'';
    let endTime = order_time.split(" - ")[1]||'';
    let orderId = $("#orderId").val();//订单号
    window.location.href = httpurl + "/ExprotRefundRecord?pname=" + pro_name + "&orderid=" + orderId + "&startTime=" + startTime + "&endTime=" + endTime + "&handle_type=" + handle_type + "&state=" + state;
}


function CreatRefundInfo(obj) {

    let datastate = $(obj).attr("data-state");
    if (datastate > 0) {
        top.layer.alert("该状态下的退款数据不能退款!!请确认后再试!!")
        return;
    }
    let money = $(obj).attr("data-info");
    let id = $(obj).attr("data-id");
    layer.open({
        type: 1,
        area: ['500px', '400px'],
        shadeClose: false, //点击遮罩关闭
        content: '<form class="am-form" style="width: 90%;margin: 0 auto;">' +
            '            <label for="username" style="font-size: 20px;">确认后，<span class="text-danger">' + money + '元</span>将退入买家账户:</label>' +
            '            <br><br><br>' +
            //'            <div class="width100">请输入退款密码:<input type="password" value=""/></div>' +
            //'            <span class="text-danger">请输入验证码</span>' +
            '            <span class="text-danger">我的备注:<textarea class="resons" value=""/></span></span>' +

            '            <div class="flex flex-wrap flex-col-3">' +
            '<div class="form-group-col-2">' +
            '<div class="form-label"></div>' +
            '<div class="form-cont padding_top10 margin_left2b">' +
            '<input type="button" onclick="addClickUpdate(this)" data-info="' + datastate + '" data-id="' + id + '" value="确认"  class="btn btn-info"/>&nbsp;&nbsp;' +
            '<input type="button" onclick="CloseLayuiAlert();" value="取消" class="btn btn-danger"/>' +

            '</div>' +
            '</div>' +
            '</div>' +
            '        </form>'
    });
}
// 退款接口
function addClickUpdate(obj) {
    let resons = $(".resons").val();
    let id = $(obj).attr('data-id');
    let datastate = $(obj).attr('data-info');
    top.layer.confirm('确认已经和客户沟通核实退款情况,确认后,该笔金额将直接退款到客户微信,是否确认？', { icon: 3, title: '提示信息' }, function (index) {
        // var index = top.layer.msg('提交中，请稍候', { icon: 16, time: 1000, shade: 0.8 });
        $.ajax({
            type: "POST",
            url: httpurl + "/updateRefundRecordListPc",
            cache: false,
            data: JSON.stringify({
                "id": id,
                "reson": resons,
                "state": datastate
            }),
            headers: {
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Methods": "*",
                "Access-Control-Allow-Headers": "Authorization",
                "Authorization": GetTokenInfo()
            },
            contentType: 'application/json',
            success: function (data) {
                layer.closeAll();
                if (data.rtnCode == 200) {
                    top.layer.msg("提交成功!!请等待到账！！");
                } else {
                    top.layer.msg(data.msg,{ time: 3000, shade: 0.8 });
                }
                timer = setTimeout(()=>{
                    clearTimeout(timer)
                    inituserdata();
                },2000)
            },
            error: function (res) {
                top.layer.msg('网络请求失败，请稍后再试');
            }
        });
    }, function () {

    });


}

function UpdateStateInfo() {
    state = $("#state option:selected").val();
    $(".mystate a").removeClass("red");
    $(".mystate a").each(function () {
        let dataid = $(this).attr("data-id");
        if (dataid == state) {
            $(this).addClass("red");
        }
    });
    SearchInfo();
}

function inituserdata() {
    // let phone = $("#phone").val();//用户手机号
    let handle_type = $("#handle_type").val();
    let pro_name = $("#pro_name").val();//宝贝名称
    // let phone = $("#phone").val();

    let order_time = $("#order_time").val();//下单时间
    let startTime = order_time.split(" - ")[0];
    let endTime = order_time.split(" - ")[1];
    let orderId = $("#orderId").val();//订单号
    var index = top.layer.msg('加载中，请稍候', { icon: 16, time: false, shade: 0.8 });
    $.ajax({
        url: httpurl + "/selectRefundRecordListPc",
        cache: false,
        data: {
            "page": pageNo,
            "pagesize": pageRecords,
            "pname": pro_name,
            "orderid": orderId,
            "startTime": startTime,
            // "phone": phone,
            "endTime": endTime,
            "handle_type": handle_type,
            "state": state,
            // "phone": endTime,
            // "sphone": orderId
        },
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "*",
            "Access-Control-Allow-Headers": "Authorization",
            "Authorization": GetTokenInfo()
        },
        contentType: 'application/json',
        success: function (data) {
            let dataHtml = "";
            if (data.rtnCode == 200) {
                let dataInfo = data.data;
                totalRecords = dataInfo[dataInfo.length - 1].total;
                if (dataInfo.length > 0) {
                    dataInfo.forEach((v,index) => {
                        let ostate = (v.state == 0 ? "申请中" : (v.state == 1 ? "退款中" : (v.state == 2 ? "退款成功" : (v.state == 3 ? "退款驳回" : (v.state == 4 ? "取消申请" : "未知")))));
                        let otype = (v.handle_type == 1 ? "未收到货" : (v.handle_type == 2 ? "已收到货" : "未知"));
                        let confirm = "";
                        let TempInfo = "";
                        if (v.state > 0) {
                            TempInfo += '<a href="#" data-id="' + v.id + '" onclick="SelectInfo(this);">查询</a>&nbsp;&nbsp;';
                        }
                        if(v.state==1||v.state==0){
                            confirm += '<a onclick="CreatRefundInfo(this);" data-id="' + v.id + '" data-state="' + v.state + '" data-info="' + v.money + '">确认退款</a>&nbsp;&nbsp;'
                        }
                        v.orderInfoList.forEach((item, i) => {
                            if(i==0){
                                let imgHtml = ''
                                if(v.img){
                                    let imglist = v.img.split(',')
                                    
                                    imglist.forEach(item=>{
                                        imgHtml += `<img style="width:100px;margin:5px 0" onclick="amplificationImg(this)" src="${item}"/>`
                                    })
                                    // console.log(imgHtml);
                                }
                                dataHtml += '<tr>' +
                                `<td rowspan="${v.orderInfoList.length}">${index+1}</td>`+
                                `<td rowspan="${v.orderInfoList.length}">${v.id}</td>`+
                                `<td rowspan="${v.orderInfoList.length}">` +
                                '<span>' + (item.orderEntity == null ? "" : item.orderEntity.name) + '</span><br/>'+
                                '<span>' + (item.orderEntity == null ? "" : item.orderEntity.phone) + '</span></td>' +
                                `<td>` +
                                '<div>' +
                                '<a class="text-info" href="../order/DetaileOrder.html?OrderId=' + v.orderid + '">' + v.orderid + '</a>' +
                                '</div>' +
                                '<div class="width100">' +
                                '<div class="width30 float_left">' +
                                '<img width="70%" id="preview" class="preview" src="' + visitimgurl + '/' + (item.productEntity == null ? "" : item.productEntity.headimg) + '"/>' +
                                '</div>' +
                                '<div class="width70 float_left">' +
                                '<span class="float_left">' + (item == null ? "" : (item.pname == null ? "" : item.pname)) + '</span><br/>' +
                                '<span class="float_left">套餐: ' + (item == null ? "" : (item.mname == null ? "" : item.mname)) + ' </span><br/>' +
                                '<span class="float_left">数量: ' + (item == null ? "" : item.num) + ' </span>' +
                                '</div>' +
                                '</div>' +
                                '</td>' +
                                `<td>￥${item.infoPayPrice}</td>`+
                                `<td rowspan="${v.orderInfoList.length}">￥` + v.money + '</td>' +
                                `<td rowspan="${v.orderInfoList.length}">`+ v.intime + '</td>' +
                                `<td rowspan="${v.orderInfoList.length}">` +
                                // v.remark
                                `<div>${v.remark}</div>` +
                                imgHtml +
                                '</td>' +
                                `<td rowspan="${v.orderInfoList.length}">` +
                                '<span class="statetext">' + ostate + '</span><br/>' +
                                '<span class="text-info" style="cursor:pointer" onclick="updateSta(this,\'' + v.state + '\');">修改</span>' +
                                '<span class="upsta" style="display: none;">' +
                                '<select class="width65 stateid" style="height: 30px;" data-info="' + v.money + '" data-id="' + v.id + '" onchange="UpdateState(this);">' +
                                '<option value="0">申请中</option>' +
                                '<option value="1">退款中</option>' +
                                '<option value="2">退款成功</option>' +
                                '<option value="3">退款驳回</option>' +
                                '<option value="4">取消申请</option>' +
                                '</select>' +
                                '</span><br/>' +
                                '</td>' +
                                `<td rowspan="${v.orderInfoList.length}">` + otype + '</td>' +
                                `<td rowspan="${v.orderInfoList.length}">`+ TempInfo +
                                confirm +
                                '</td>' +
                                '</tr>';
                            }else {
                                dataHtml +=
                                '<td>' +
                                '<div>' +
                                '<a class="text-info" href="../order/DetaileOrder.html?OrderId=' + v.orderid + '">' + v.orderid + '</a>' +
                                '</div>' +
                                '<div class="width100">' +
                                '<div class="width30 float_left">' +
                                '<img width="70%" id="preview" class="preview" src="' + visitimgurl + '/' + (item.productEntity == null ? "" : item.productEntity.headimg) + '"/>' +
                                '</div>' +
                                '<div class="width70 float_left">' +
                                '<span class="float_left">' + (item == null ? "" : (item.pname == null ? "" : item.pname)) + '</span><br/>' +
                                '<span class="float_left">套餐: ' + (item == null ? "" : (item.mname == null ? "" : item.mname)) + ' </span><br/>' +
                                '<span class="float_left">数量: ' + (item == null ? "" : item.num) + ' </span>' +
                                '</div>' +
                                '</div>' +
                                '</td>' +
                                '<td>￥' + item.infoPayPrice + '</td>' +
                                '</tr>';
                            }
                        })

                    })
                } else {
                    totalRecords = 0;
                    dataHtml += '<tr>'
                        + '<td colspan="12" style="text-align:center;padding: 20px 0">暂无数据</td>'
                        + '</tr>';
                }
            } else {
                totalRecords = 0;
                dataHtml += '<tr>'
                    + '<td colspan="12" style="text-align:center;padding: 20px 0">暂无数据</td>'
                    + '</tr>';
            }

            $("#tableInfo tbody").html(dataHtml);
            top.layer.closeAll();
            page();
        }, error: function () {
            top.layer.closeAll();
            top.layer.alert("加载失败,请检查网络设置!!")
        }

    });

}
function SelectInfo(obj) {
    let id = $(obj).attr("data-id");
    var index = top.layer.msg('加载中，请稍候', { icon: 16, time: false, shade: 0.8 });
    $.ajax({
        url: httpurl + "/refundRecordSate",
        cache: false,
        data: {
            "id": id
        },
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "*",
            "Access-Control-Allow-Headers": "Authorization",
            "Authorization": GetTokenInfo()
        },
        contentType: 'application/json',
        success: function (data) {
            top.layer.closeAll();
            if (data.rtnCode == 500) {
                top.layer.msg(data.msg)
                return;
            }
            let DataList = JSON.parse(data.msg);
            let dataInfo = '<table class="table table-bordered text-center"><tbody>' +
                '<tr>' +
                '<td>微信订单号:' + DataList.outTradeNo + '</td>' +
                '<td>商户订单号:' + DataList.transactionId + '</td>' +
                '</tr>' +
                '<tr>' +
                '<td>订单金额:' + DataList.totalFee / 100 + '</td>' +
                '<td>申请退款金额:' + (DataList.refundRecords[0].refundFee) / 100 + '</td>' +
                '</tr>' +
                '<tr>' +
                '<td>商户退款单号:' + DataList.refundRecords[0].outRefundNo + '</td>' +
                '<td>订单总退款次数:' + DataList.refundCount + '</td>' +
                '</tr>' +
                '<tr>' +
                '<td>退款渠道:' + DataList.refundRecords[0].refundChannel + '</td>' +
                '<td>退款状态:' + DataList.refundRecords[0].refundStatus + '</td>' +
                '</tr>' +
                '<tr>' +
                '<td>退款入账账户:' + DataList.refundRecords[0].refundRecvAccount + '</td>' +
                '<td>退款成功时间:' + DataList.refundRecords[0].refundSuccessTime + '</td>' +
                '</tr>' +
                '<tr>' +
                '<td colspan="2">' +
                '<div class="form-cont">' +
                '<input type="button"  onclick="CloseLayuiAlert();" value="确认"  class="btn btn-info"/>&nbsp;&nbsp;' +
                '<input type="button" onclick="CloseLayuiAlert();" value="取消" class="btn btn-danger"/>' +

                '</div>' +
                '</td>' +
                '</tr>' +
                '</tbody></table>';
            layer.open({
                type: 1,
                area: ['800px', '400px'],
                shadeClose: false, //点击遮罩关闭
                content: dataInfo
            });
        }
    });

}
function CloseLayuiAlert() {
    layer.closeAll();
}
function updateSta(obj, state) {
    $(obj).hide();
    console.log(state, "===state");
    $(".stateid option[value='" + state + "']").attr("selected", "selected");
    $(obj).parent().find(".upsta").show();
}

function UpdateState(obj) {
    let state = $(obj).find("option:selected").val();
    let id = $(obj).attr("data-id");
    let money = $(obj).attr("data-info");

    if (state == 1) {//退款的话,不能在这里点击
        top.layer.alert("请不要在此处修改退款!!", function () {
            top.layer.closeAll();
            inituserdata();
        })
        
        return;
    }
    top.layer.confirm('确认提交？', { icon: 3, title: '提示信息' }, function (index) {
        var index = top.layer.msg('提交中，请稍候', { icon: 16, time: false, shade: 0.8 });
        $.ajax({
            type: "POST",
            url: httpurl + "/updateRefundRecordSate",
            cache: false,
            data: JSON.stringify({
                "id": id,
                "state": state
            }),
            headers: {
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Methods": "*",
                "Access-Control-Allow-Headers": "Authorization",
                "Authorization": GetTokenInfo()
            },
            contentType: 'application/json',
            success: function (data) {
                top.layer.alert(data.msg, function () {
                    top.layer.closeAll();
                    inituserdata();
                });

            }
        });
    }, function () {

    });
}

function SearchInfo() {
    pageNo = 1;
    inituserdata();
}

//分页
function page() {
    laypage.render({
        elem: 'page' //注意，这里的 test1 是 ID，不用加 # 号
        , count: totalRecords //数据总数，从服务端得到
        , curr: pageNo //获取起始页 location.hash.replace('#!fenye=', '')
        , hash: 'fenye' //自定义hash值
        , layout: ['count', 'prev', 'page', 'next', 'skip']
        , limit: pageRecords
        , jump: function (obj, first) {
            //首次不执行
            if (!first) {
                pageNo = obj.curr;
                pageRecords = obj.limit;// 当前页面记录数
                inituserdata();
            }
        }
    });
}

function ClearSearchInfo() {
    $("#pro_name").val(""); //宝贝名称
    $("#handle_type").val(""); 
    $("#order_time").val(""); //下单时间
    $("#orderId").val(""); //订单号
    $("#state").val("-1");
    state = -1
}

// 放大图片
function amplificationImg(obj) {
    let url = $(obj).attr("src");
    console.log(url);
    $("#displayImg").attr("src", url);
    var height = $("#displayImg").height();//拿的图片原来宽高，建议自定义宽高
    var width = $("#displayImg").width();
    layer.open({
        type: 1,
        title: false,
        closeBtn: 0,
        shadeClose: true,
        area: [width + 'px', height + 'px'], //宽高
        content: "<img src=" + url + " />"
    });
}